/*
 * MinIO Cloud Storage (C) 2018 MinIO, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import React from "react";
import { connect } from "react-redux"
import { createStyles, makeStyles, withStyles, Theme } from '@material-ui/core/styles';
import FormControl from '@material-ui/core/FormControl';
import InputLabel from '@material-ui/core/InputLabel';
import MenuItem from '@material-ui/core/MenuItem';
import Select from '@material-ui/core/Select';
import InputBase from '@material-ui/core/InputBase';
import ReactEcharts from 'echarts-for-react';
import * as echarts from 'echarts';
import Alert from '@material-ui/lab/Alert';
import IconButton from '@material-ui/core/IconButton';
import Collapse from '@material-ui/core/Collapse';
import CloseIcon from '@material-ui/icons/Close';
import api from "../../../common/api";
import { ChartUrl, timeConvert, beforeNowtimeByMinu } from "./types";
// import * as from "./actions"

const BootstrapInput = withStyles((theme: Theme) =>
  createStyles({
    root: {
      'label + &': {
        marginTop: 0,
        marginLeft: theme.spacing(4),
      },
    },
    input: {
      borderRadius: 4,
      position: 'relative',
      backgroundColor: theme.palette.background.paper,
      border: '1px solid #ced4da',
      fontSize: 14,
      padding: '5px 26px 5px 12px',
      transition: theme.transitions.create(['border-color', 'box-shadow']),
      '&:focus': {
        borderRadius: 4,
        borderColor: '#80bdff',
        boxShadow: '0 0 0 0.2rem rgba(0,123,255,.25)',
      },
    },
  }),
)(InputBase);
const styles = (theme: Theme) =>
  createStyles({
    alert: {
      position: "absolute",
      width: "100%",
      textAlign: "center",
      zIndex: 1000, 
      top: 35
    },
    alertPop: {
      margin: "0 auto",
      width: "130px"
    },
    chart: {
      height: '290px !important', 
      width: '100%', 
      marginTop: -20,
      marginBottom: -40
    },
});
interface ChartState {
  classes: any;
  // inputStep: string,
}
export class D_NodeS3 extends React.Component<ChartState, any> {
  constructor(props:any){
    super(props);
    this.state = {
      records: [],
      legend:[],
      xrecord:[],
      recordsData:[],
      xrecord2:[],
      recordsData2:[],
      loading: false,
      step: "14",
      dataWarn:"",
      open: false
    };
  };
  setOpen(a:boolean){
    this.setState({
      open: a
    })
  }
  getChart() {
    // let duration = 60;
    // if(step == '1'){
    //   duration = 15
    // }else if(step == '7'){
    //   duration = 30
    // }else if(step == '14'){
    //   duration = 60
    // }else if(step == '28'){
    //   duration = 120
    // }else if(step == '86'){
    //   duration = 360
    // }else if(step == '172'){
    //   duration = 720
    // }else if(step == '345'){
    //   duration = 1440
    // }
    // 发送字节
    let url = ChartUrl+"s3_tx_bytes_total&start="+Date.parse(beforeNowtimeByMinu(60)).toString().substring(0,10)+"&end="+Date.parse(beforeNowtimeByMinu(0)).toString().substring(0,10)+"&step=14";
    api
      .invoke("GET", url)
      .then((res) => {
        var xrec = new Array();
        var rootData = res.data.result;
        if(rootData != []){
          for(var i=0;i<rootData.length;i++){
            for(var a=0;a<rootData[i].values.length;a++){
              rootData[i].values[a][0] = timeConvert(parseInt(rootData[i].values[a][0]));
              rootData[i].values[a][1] = parseFloat(rootData[i].values[a][1]);
            }
          }
          
          for(var i=1;i<rootData.length;i++){
            for(var a=0;a<rootData[i].values.length;a++){
              rootData[0].values[a][1] += rootData[i].values[a][1]
            }
          }
          // console.log(rootData[0].values)
          // console.log(rootData);
          var data = rootData[0].values;
          for(var n=0;n<data.length;n++){
            xrec[n]=data[n][0]
          }
          let recData = rootData[0].values
          // console.log(recData);
          this.setState({
            xrecord: xrec,
            recordsData: recData,
          });
        }else{
          this.setState({
            dataWarn: "暂无数据",
            loading: false 
          })
          this.setOpen(true);
        }
      })
      .catch(err => {this.setState({
          dataWarn: "暂无数据",
          loading: false 
        })
        this.setOpen(true);
      });

    // 接收字节
    let url2 = ChartUrl+"s3_rx_bytes_total&start="+Date.parse(beforeNowtimeByMinu(60)).toString().substring(0,10)+"&end="+Date.parse(beforeNowtimeByMinu(0)).toString().substring(0,10)+"&step=14";
    api
      .invoke("GET", url2)
      .then((res) => {
        var xrec2 = new Array();
        var rootData2 = res.data.result;
        if(rootData2 != []){
          for(var i=0;i<rootData2.length;i++){
            for(var a=0;a<rootData2[i].values.length;a++){
              rootData2[i].values[a][0] = timeConvert(parseInt(rootData2[i].values[a][0]));
              rootData2[i].values[a][1] = parseFloat(rootData2[i].values[a][1]);
            }
          }
          
          for(var i=1;i<rootData2.length;i++){
            for(var a=0;a<rootData2[i].values.length;a++){
              rootData2[0].values[a][1] += rootData2[i].values[a][1]
            }
          }
          // console.log(rootData[0].values)
          // console.log(rootData);
          var data = rootData2[0].values;
          for(var n=0;n<data.length;n++){
            xrec2[n]=data[n][0]
          }
          let recData2 = rootData2[0].values
          // console.log(recData);
          this.setState({
            xrecord2: xrec2,
            recordsData2: recData2,
          });
        }else{
          this.setState({
            dataWarn: "暂无数据",
            loading: false 
          })
          this.setOpen(true);
        }
      })
      .catch(err => {this.setState({
          dataWarn: "暂无数据",
          loading: false 
        })
        this.setOpen(true);
      });
  }
  componentDidMount(): void {
    var that = this
    that.getChart();
    var timer = setInterval(() => {
      let url = window.location.href
      if(url.indexOf("/dashboard") != -1){
        that.getChart();
      }else{
        clearInterval(timer)
      }
    }, 30000)
  }
  getOption= () => ({
    color: ['#5793f3', '#91c7ae'],
    tooltip: {
      trigger: 'none',
      axisPointer: {
        type: 'cross'
      }
    },
    legend: {
      top:"24",
      data:['发送字节', '接收字节']
    },
    grid: {
      left: 35,
      right: 10,
      top: 70,
      bottom: 50
    },
    xAxis: [
      {
        type: 'category',
        boundaryGap: false,
        axisTick: {
          alignWithLabel: true
        },
        axisLine: {
          onZero: false,
          lineStyle: {
            color: '#5793f3'
          }
        },
        axisPointer: {
          label: {
            formatter: function (params:any) {
              return '发送 ' + params.value
                + (params.seriesData.length ? '：' + params.seriesData[0].data[1]+"B" : '');
            }
          }
        },
        data: this.state.xrecord
      },
      {
        type: 'category',
        axisTick: {
          alignWithLabel: true
        },
        axisLine: {
          onZero: false,
          lineStyle: {
            color: '#91c7ae'
          }
        },
        axisPointer: {
          label: {
            formatter: function (params:any) {
              return '接收 ' + params.value
                + (params.seriesData.length ? '：' + params.seriesData[0].data[1]+"B" : '');
            }
          }
        },
        data: this.state.xrecord2
      }
    ],
    yAxis: [
      {
        name: 'B',
        type: 'value'
      }
    ],
    series: [
      {
        name: '发送字节',
        type: 'line',
        itemStyle: {
          color: '#5793f3'
        },
        areaStyle: {
          // @ts-ignore
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                offset: 0,
                color: 'rgba(170,200,249,0.6)'
            }, {
                offset: 1,
                color: 'rgba(87,147,243,0.8)'
            }])
        },
        xAxisIndex: 1,
        smooth: true,
        data: this.state.recordsData
      },
      {
        name: '接收字节',
        type: 'line',
        itemStyle: {
          color: '#91c7ae'
        },
        areaStyle: {
          // @ts-ignore
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                offset: 0,
                color: 'rgba(199,240,221,0.6)'
            }, {
                offset: 1,
                color: 'rgba(145,199,174,0.8)'
            }])
        },
        smooth: true,
        data: this.state.recordsData2
      }
    ]
  });
  render() {
    const { classes } = this.props;
    // var handleChange = (event: React.ChangeEvent<{ value: unknown }>) => {
    //   this.setState({ 
    //     step: event.target.value
    //   });
    //   this.getChart(event.target.value as string)
    // };
    return (
      <div style={{position: "relative"}}>
        {this.state.open ? (
        <div className={classes.alert}>
          <Collapse in={this.state.open} className={classes.alertPop}>
            <Alert severity="error" style={{padding: "0 16px"}}>
              {this.state.dataWarn}
            </Alert>
          </Collapse>
        </div>
        ):(
          <ReactEcharts
          ref="chart"
          option={this.getOption()}
          className={classes.chart}/>
          )}
      </div>
    );
  }
};
export default withStyles(styles)(D_NodeS3)